package com.cisdi.info.simple.util;

import com.cisdi.info.simple.annotation.DEntity;
import com.cisdi.info.simple.entity.base.BaseEntity;
import com.cisdi.info.simple.entity.base.EntityClass;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EntityManager {
    private static Logger logger = LogManager.getLogger();

    public static Map<String,EntityClass> entityClassesByClassName  = new HashMap<String,EntityClass>();
    public static Map<String,EntityClass> entityClassesByTableName  = new HashMap<String,EntityClass>();
    public static Map<String,String> tableNames2ClassNames = new HashMap<String,String>();
    public static Map<String,String> classNames2TableNames = new HashMap<String,String>();
    static
    {
        String packageNames = "com.cisdi.info,com.ddd";
        List<Class<? extends BaseEntity>> classes = ClassUtil.getClassListByAnnotation(packageNames, DEntity.class) ;
        for(Class<? extends BaseEntity> clazz : classes)
        {
            EntityClass entityClass = new EntityClass(clazz);
            if(entityClassesByClassName.containsKey(entityClass.getClassName()))
            {
                logger.error("实体类名定义重复："+entityClass.getClassName());
            }
            if(entityClassesByTableName.containsKey(entityClass.getTableName()))
            {
                logger.error("数据库表明重复："+entityClass.getTableName());
            }
            entityClassesByClassName.put(entityClass.getClassName(), entityClass);
            entityClassesByTableName.put(entityClass.getTableName(), entityClass);
            classNames2TableNames.put(entityClass.getClassName(), entityClass.getTableName());
            tableNames2ClassNames.put(entityClass.getTableName(),entityClass.getClassName());

        }
        logger.info(String.format("提取到%d个实体", entityClassesByClassName.size()));
    }

    public EntityClass getEntityClassByClassName(String className)
    {
        return  entityClassesByClassName.get(className);
    }
    public EntityClass getEntityClassByTableName(String tableName)
    {
        return  entityClassesByTableName.get(tableName);
    }

}
